<template>
    <div>
        <div class="container user-basic-box e-m-h-auto e-m-b-15">
            <el-page-header @back="goBack" content="部门详情"></el-page-header>
            <div class="user-face">
                <div class="avatar">
                    <el-avatar icon="el-icon-s-shop" :size="100"></el-avatar>
                </div>
            </div>
            <div class="name">{{ details.department }}</div>
            <div class="e-p-t-5 e-p-b-5">
                <el-tag type="success" size="mini" v-if="details.user">已绑定</el-tag>
                <el-tag type="danger" size="mini" v-else>未绑定</el-tag>
            </div>
            <div v-if="details.user">
                <span class="tips e-font-14">绑定人：{{ details.user.name }}</span>
            </div>
            <div class="basic flex">
                <div class="item"><i class="el-icon-alarm-clock"></i><span>部门创建时间：{{ details.regdate }}</span></div>
                <div class="item" v-if="details.user"><el-link type="primary" @click="unbinding"><i class="el-icon-link"></i>解绑部门负责人</el-link></div>
                <div class="item" v-else><el-link type="primary" @click="dialogVisible = true"><i class="el-icon-link"></i>选择部门负责人，执行绑定操作</el-link></div>
            </div>

            <div class="admin-statistics-content e-m-t-30">
                <div class="item e-flex-1">
                    <label>订单数</label>
                    <div><span class="num">{{ orderRecord.onlinecount }}</span><small>线上单</small>，<span class="num">{{ orderRecord.offlinecount }}</span><small>线下单</small></div>
                </div>
                <div class="item e-flex-1">
                    <label>订单总重量</label>
                    <div><span class="num">{{ orderRecord.weight }}</span><small>KG</small></div>
                </div>
                <div class="item e-flex-1">
                    <label>减碳量</label>
                    <div><span class="num">{{ orderRecord.carbon }}</span><small>KG</small></div>
                </div>
            </div>
            <div class="admin-statistics-content e-m-t-15">
                <div class="item e-flex-1">
                    <label>回收收益</label>
                    <div><span class="num">{{ orderRecord.amount }}</span><small>元</small></div>
                </div>
                <div class="item e-flex-1">
                    <label>累计提现</label>
                    <div><span class="num">{{ details.cashout }}</span><small>元</small></div>
                </div>
                <div class="item e-flex-1">
                    <label>钱包余额</label>
                    <div><span class="num">{{ details.balance }}</span><small>元</small></div>
                </div>
            </div>
            <div class="admin-statistics-content e-m-t-15">
                <div class="item e-flex-1">
                    <label>积分余额</label>
                    <div><span class="num">{{ details.integral }}</span><small>分</small></div>
                </div>
                <div class="item e-flex-1"></div>
                <div class="item e-flex-1"></div>
            </div>
        </div>
        <div class="">
            <!-- <div class="container e-m-h-auto e-m-b-15">
                <el-form label-width="160px">
                    <h4>用户信息</h4>
                    <div class="flex">
                        <div class="e-flex-1">
                            <el-form-item label="客户组编号:">
                                <span>{{ details.ysid }}</span>
                            </el-form-item>
                        </div>
                        <div class="e-flex-1">
                            <el-form-item label="联系人:">
                                <span v-if="details.isactive">{{ details.contactname }}</span>
                                <span v-else>--</span>
                            </el-form-item>
                        </div>
                        <div class="e-flex-1">
                            <el-form-item label="电话:">
                                <span>{{ details.mobile ? details.mobile : '--' }}</span>
                            </el-form-item>
                        </div>
                    </div>
                </el-form>
            </div> -->
            <div class="container e-m-h-auto e-m-b-15">
                <h4>各品类回收汇总</h4>
                <div class="e-p-b-15">
                    <el-form ref="form" :model="dateForm" label-width="100px" style="border-bottom: 1px solid var(--light);">
                        <el-form-item label="时间范围">
                        <el-radio-group v-model="dateForm.timeType" size="small" @input="chageTime">
                            <el-radio-button v-for="(item,index) in dateForm.timeTypeArr" :key="index" :label="item.id">{{ item.name }}</el-radio-button>
                        </el-radio-group>
                        </el-form-item>
                        <el-form-item label="自定义日期" v-if="dateForm.timeType == 9">
                            <el-date-picker size="small" v-model="dateForm.date" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="chageTime"
                                :picker-options="expireTimeOPtion" :unlink-panels="true">
                            </el-date-picker>
                        </el-form-item>
                    </el-form>
                </div>
                <el-table ref="multipleTable" tooltip-effect="dark" :data="orderRecord.orderdetails" :span-method="objectSpanMethod" show-summary :summary-method="getSummaries" stripe border style="width: 100%;">
                    <el-table-column prop="large" label="类型" width="180">
                    </el-table-column>
                    <el-table-column prop="name" label="小类">
                    </el-table-column>
                    <el-table-column prop="weight" label="数量（KG/件）">
                        <template slot-scope="scope">
                            <span v-if="scope.row.weight > 0">{{ scope.row.weight }}</span>
                            <span v-else-if="scope.row.quantity > 0">{{ scope.row.quantity }}件</span>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额（元）">
                    </el-table-column>
                </el-table>
            </div>
            <div class="container e-m-h-auto e-m-b-15">
                <h4>最新订单</h4>
                <el-table :data="orderRecord.orderList" style="width: 100%">
                    <el-table-column fixed prop="number" label="编号" width="180">
                    </el-table-column>
                    <el-table-column prop="enterprise" label="部门">
                        <template slot-scope="scope">
                            <span v-if="scope.row.enterprise">{{ scope.row.enterprise.department }}</span>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额（元）">
                    </el-table-column>
                    <el-table-column prop="payway" label="结算方式">
                    </el-table-column>
                    <el-table-column prop="createddatetime" label="下单时间">
                    </el-table-column>
                    <el-table-column prop="state" label="状态">
                        <template slot-scope="scope">
                            <!-- <span class="color-success"
                                v-if="scope.row.state == '已接单' || scope.row.state == '已回收' || scope.row.state == '已入库'">{{
                                    scope.row.state
                                }}</span>
                            <span class="color-danger"
                                v-else-if="scope.row.state == '待派单' || scope.row.state == '待接单' || scope.row.state == '待上门' || scope.row.state == '待付款' || scope.row.state == '待入库'">{{
                                    scope.row.state
                                }}</span>
                            <span class="color-warning" v-else>{{ scope.row.state }}</span> -->
                            <span class="color-success">{{ scope.row.state }}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="container e-m-h-auto e-m-b-15">
                <h4>提现记录</h4>
                <el-table :data="orderRecord.cashrecord" style="width: 100%">
                    <el-table-column fixed prop="number" label="编号" width="180">
                    </el-table-column>
                    <el-table-column prop="billdetailnumber" label="流水编号">
                    </el-table-column>
                    <el-table-column prop="examinedate" label="提现时间">
                    </el-table-column>
                    <el-table-column prop="username" label="提现人">
                    </el-table-column>
                    <el-table-column prop="amount" label="提现金额">
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="container e-m-h-auto e-m-t-15">
            <h4>积分列表记录</h4>
            <el-table :data="listIntegral.list" style="width: 100%" class="e-m-t-15">
                <el-table-column prop="number" label="编号">
                </el-table-column>
                <el-table-column prop="type" label="类别">
                </el-table-column>
                <el-table-column prop="balance" label="积分">
                </el-table-column>
                <el-table-column prop="amount" label="价值（元）">
                </el-table-column>
                <el-table-column prop="createddatetime" label="时间">
                </el-table-column>
                <el-table-column prop="remarks" label="备注">
                </el-table-column>
            </el-table>
            <div class="table-pagination">
                <el-pagination background layout="total, prev, pager, next" :total="listIntegral.total" :page-sizes="[10, 50, 100, 200]"
                    :page-size="listIntegral.pageSize" :current-page="listIntegral.page" @current-change="getListIntegral">
                </el-pagination>
            </div>
        </div>
        <!-- 绑定用户 -->
        <el-dialog title="绑定用户" :visible.sync="dialogVisible" width="500px">
            <el-form :model="bindForm" ref="ruleForm" label-width="120px">
                <el-form-item label="选择用户">
                    <el-select v-model="bindForm.id" placeholder="请输入用户关键词搜索" filterable remote reserve-keyword :remote-method="binding">
                        <el-option v-for="item in userlist" :key="item.id" :label="item.name" :value="item.id">
                            <span style="float: left">{{ item.name }}</span>
                            <span style="float: right;color:var(--grey)">{{ item.mobile }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="bindUser">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    layout: 'admin',
    head() {
        return {
            title: '部门详情' 
        }
    },
    props: {
        id:{
            type: Number,
            default: 0
        },
        eid:{
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            loading: false,
            dialogVisible: false,
            details: {
                user:{}
            },
            orderRecord: {
                balance: 0,
                carbon: 0,
                cashout: 0,
                cashrecord: [],
                income: 0,
                ordercount: 0,
                orderdetails: [],
                orderList: [],
                regdays: 0,
                weight: 0,
            },
            bindForm: {
                id: null
            },
            userlist: [],
            // 时间选择
            dateForm: {
                timeType: 0,
                timeTypeArr:[
                    {
                        id:0,
                        name: '全部'
                    },
                    {
                        id:1,
                        name: '今日'
                    },
                    {
                        id:2,
                        name: '昨日'
                    },
                    {
                        id:3,
                        name: '本月'
                    },
                    {
                        id:4,
                        name: '上月'
                    },
                    {
                        id:5,
                        name: '本季度'
                    },
                    {
                        id:6,
                        name: '上季度'
                    },
                    {
                        id:7,
                        name: '本年'
                    },
                    {
                        id:8,
                        name: '上年'
                    },
                    {
                        id:9,
                        name: '自定义日期'
                    }
                ],
                date: []
            },
            expireTimeOPtion: {
                disabledDate(time) {
                    return time.getTime() > Date.now() - 8.64e6;  //如果没有后面的-8.64e6就是不可以选择今天的 
                }
            },
            listIntegral: {
                list: [],
                page: 1,
                pageSize: 10,
                total: 0
            }
        };
    },
    mounted() { 
        this.getview(this.id)
        this.getSumByType()
        this.getWithdrawApply()
        this.getEnterpriseOrder()
        this.getListIntegral()
    },
    methods: {
        getview(id) {//部门详情
            return this.$axios.get('/Enterprise/Detail?id=' + id).then((res) => {
                console.log(res)
                this.details = res
                // this.orderRecord = res.orders
                if (res.promotionuser) {
                    this.promotion = [res.promotionuser]
                } else {
                    this.promotion = []
                }
            })
        },
        // 获取最新订单
        getEnterpriseOrder(){
            this.$axios.post('/User/Order/List', {
                pageIndex: 1,
                pageSize: 10,
                enterpriseId: this.id,
                userType: 1, //用户类型：0全部，1客户组订单，2用户订单
                timeType: 9,
                startDate: this.start,
                endDate: this.end
            }).then((res) => {
                this.orderRecord.orderList = res.rows
            })
        },
        getSumByType(param = null){
            if(param == null){
                param = {
                    timeType: this.dateForm.timeType,
                    isDepartment: false,
                    enterpriseId: this.id,
                    orderType: null, //订单类型：null全部，1.线上单，2.线下单
                    userType: 1, //用户类型：0全部，1客户组订单，2用户订单
                    includeDepartment: false, //是否包含下级部门(EnterpriseId>0时有效)
                }
            }
            this.$axios.post(`/User/Order/SumByType`,param).then((res)=>{
                console.log('SumByType',res)
                // this.orderRecord.orderdetails = res.largetype
                let dataArray = []
                res.largetype.forEach((item,index)=>{
                    item.product.forEach((cell,i)=>{
                        dataArray.push({
                            id: cell.id,
                            typeId: cell.typeId,
                            name: cell.name,
                            quantity: cell.quantity,
                            weight: cell.weight,
                            amount: cell.amount,
                            large: item.name,
                            sort: cell.sort,
                            isweighing: cell.isweighing
                        })
                    })
                })

                this.orderRecord.orderdetails = dataArray
                this.orderRecord.amount = res.amount // 总金额
                this.orderRecord.weight = res.weight // 总重量
                this.orderRecord.carbon = res.carbon //总减碳量
                this.orderRecord.quantity = res.quantity // 总件数
                this.orderRecord.onlinecount = res.onlinecount // 统计线上单数量
                this.orderRecord.offlinecount = res.offlinecount // 统计线下单数量
            })
        },
        //合并类型格子
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            let mergeLength = [0];//需要进行横纵合并的列,0开始
            for (let j = 0; j < mergeLength.length; j++) {
                if (columnIndex == mergeLength[j]) {
                    let finArray = [1, 1];
                    // 处理行数据
                    let cgname = 'large' //合并单元格的主键依据，一般为第一列的值
                    if (rowIndex === 0 || row[cgname] !== this.orderRecord.orderdetails[rowIndex - 1][cgname]) {
                        let rowspan = 1;
                        //计算需要进行合并操作的行
                        for (let i = 0; i < this.orderRecord.orderdetails.length - 1; i++) {
                            // 只合并连续的
                            if (this.orderRecord.orderdetails[i][cgname] === row[cgname] && this.orderRecord.orderdetails[i + 1][cgname] === row[cgname]) {
                                rowspan++;
                            }
                        }
                        finArray[0] = rowspan;
                    } else {
                        finArray[0] = 0;
                    }
                    return finArray
                }
            }
        },
        //合并最后一个合计
        getSummaries(param) {
            const sums = []
            sums[0] = '合计'
            sums[1] = '/'
            sums[2] = (this.orderRecord.weight).toFixed(2) + 'KG' + ' / ' + this.orderRecord.quantity + '件'
            sums[3] = this.orderRecord.amount
            return sums;
            // sums数组的每一个元素代表表格从左到右的列(column)。
        },
        // 获取最新订单
        getEnterpriseOrder(){
            this.$axios.post('/User/Order/List', {
                pageIndex: 1,
                pageSize: 10,
                enterpriseId: this.id,
                userType: 1, //用户类型：0全部，1客户组订单，2用户订单
                timeType: 9,
                startDate: this.start,
                endDate: this.end
            }).then((res) => {
                this.orderRecord.orderList = res.rows
            })
        },
        // 提现申请列表
        getWithdrawApply(){
            this.$axios.post('/WithdrawApply/List', {
                pageIndex: 1,
                pageSize: 10,
                userType: '客户组', //用户类型
                relationId: this.id,
                // isIncludeDepartment: true, //是否包含部门（UserType=客户组，且RelationId>0时有效）
                state: [],
                // timeType: 9,
                // startDate: this.start,
                // endDate: this.end
            }).then((res) => {
                console.log('提现申请列表',res)
                this.orderRecord.cashrecord = res.rows
            })
        },
        getListIntegral(pageIndex){
            if(pageIndex){
                this.listIntegral.pageIndex = pageIndex
            }else{
                this.listIntegral.pageIndex = 1
            }
            //用户积分列表 
            this.$axios.post('/Bill/List', {
                pageIndex: this.listIntegral.pageIndex,
                pageSize: this.listIntegral.pageSize,
                enterpriseId: this.id,
                timeType: 9,
                startDate: this.start,
                endDate: this.end
            }).then((res) => {
                this.listIntegral.list = res.rows
                this.listIntegral.total = res.total
            })
        },
        bindUser() { //绑定用户
            this.$axios.post('/Enterprise/Bind', {
                userId: this.bindForm.id,
                id: this.id
            }).then((res) => {
                this.$message.success(res.msg);
                this.getview(this.id)
                this.dialogVisible = false
            })
        },
        binding(key) {//请求所有用户
            this.loading = true
            this.$axios.post('/User/List', {
                "pageIndex": 1,
                "pageSize": 10,
                "key": key?key:'',
                "type": 1
            }).then((res) => {
                this.dialogVisible = true
                this.loading = false
                this.userlist = res.rows
            }).catch(()=>{
                this.loading = false
            })
        },
        unbinding() { //解绑部门负责人
            this.$confirm('您确定要解绑部门负责人吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post('/Enterprise/UnBind',[this.id]).then((res) => {
                    this.$message.success(res.msg);
                    this.getview(this.id)
                    // this.getOrderRecord(this.id)
                })
            })
        },
        
        goBack() {
            this.$emit('goBack')
        },
        // 选择时间筛选回收汇总
        chageTime(e){
            let param = {
                timeType: this.dateForm.timeType,
                isDepartment: false,
                enterpriseId: this.id,
                orderType: null, //订单类型：null全部，1.线上单，2.线下单
                userType: 1, //用户类型：0全部，1客户组订单，2用户订单
                includeDepartment: false, //是否包含下级部门(EnterpriseId>0时有效)
            }

            // 判断是否为自定义时间筛选回收统计
            if(this.dateForm.timeType == 9){
                try {
                    param.startTime = e[0]
                    param.endTime = e[1]
                } catch (e) {
                    console.log('选择自定义日期筛选回收统计错误：',e)
                }
                
                if(!param.startTime||!param.endTime){
                    return
                }
            }else{
                this.dateForm.date = []
            }
            
            // this.$axios.post(`User/Order/SumByType`,param).then((res)=>{
            //     console.log('GetTypeDetail',res)
            //     // this.orderRecord.orderdetails = res.largetype
            // })
            
            this.getSumByType(param)
        }
    }
};
</script>
<style lang="scss" scoped>
.box {
    margin-top: 35px;

    h4 {}

    text-align: left;
}

.user-basic-box {
    // background: url(/images/bg.jpg);
    background-size: 100%;
    text-align: center;

    .user-face {
        text-align: center;
        width: 100px;
        margin: 0 auto;
        position: relative;

        .avatar {
            .iconfont {
                font-size: 14px;
                position: absolute;
                right: 3px;
                bottom: 26px;
                background-color: #fff;
                height: 22px;
                width: 22px;
                line-height: 24px;
                border-radius: 100%;
            }

            .male {
                background: var(--blue);
                color: #fff;
            }

            .female {
                background: var(--pink);
                color: #fff;
            }
        }
    }

    .basic {
        font-size: 14px;
        align-items: center;
        justify-content: center;
        margin-top: 15px;

        .item {
            margin: 0 10px;
        }
    }
}

.admin-statistics-content {
    display: flex;

    .item {
        &+.item {
            border-left: 1px solid var(--light);
            padding-left: 30px;
        }

        .icon {
            width: 44px;
            height: 44px;
            border-radius: 50%;
            border: 1px solid var(--light);
            background-color: #f2f3f5;
            padding: 5px;
            margin: 0 20px 0 0;
            box-shadow: 3px 2px 11px 0 rgb(70 70 70 / 22%);
        }

        label {
            color: var(--grey);
            font-size: 12px;
            margin-bottom: 5px;
            display: block;
        }

        .num {
            font-size: 30px;
        }
    }
}

.statistics-content {
    display: flex;

    .item {
        &+.item {
            border-left: 1px solid var(--light);
            padding-left: 30px;
        }

        .icon {
            width: 44px;
            height: 44px;
            border-radius: 50%;
            border: 1px solid var(--light);
            background-color: #f2f3f5;
            padding: 5px;
            margin: 0 20px 0 0;
            box-shadow: 3px 2px 11px 0 rgb(70 70 70 / 22%);
        }

        label {
            color: var(--grey);
            font-size: 12px;
            margin-bottom: 5px;
            display: block;
        }

        .num {
            font-size: 30px;
        }
    }
}
</style>